package com.zhanghe.im.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.Date;

public class FirstClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date()+":客户端写出数据");
        for(int i=0;i<1000;i++){
            ByteBuf buffer = getByteBuf(ctx);
            ctx.channel().writeAndFlush(buffer);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buteBuf = (ByteBuf)msg;
        System.out.println(new Date()+":客户端读到数据-> "+buteBuf.toString(Charset.forName("utf-8")));
    }

    private ByteBuf getByteBuf(ChannelHandlerContext ctx){
        //获取二进制抽象 bytebuf
        ByteBuf buffer = ctx.alloc().buffer();
        //准备数据
        //byte[] bytes = new String("hello world").getBytes(Charset.forName("utf-8"));
        byte[] bytes = "你好，欢迎关注我的微信公众号，《闪电侠的博客》!".getBytes(Charset.forName("utf-8"));
        //填充数据
        buffer.writeBytes(bytes);
        return buffer;
    }
}
